import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:ycbl/config/bl_color.dart';
import 'package:ycbl/config/bl_style.dart';
import 'package:ycbl/config/route_manager.dart';
import 'package:ycbl/utils/toast_util.dart';
import 'package:ycbl/view_model/login_view_model.dart';
import 'package:ycbl/widget/bl_app_bar.dart';
import 'package:ycbl/widget/bl_button_controller.dart';
import 'package:ycbl/widget/border_label.dart';
import 'package:ycbl/widget/gradient_btn.dart';
import 'package:ycbl/widget/login_field_widget.dart';
import 'package:ycbl/widget/provider/bl_provider_widget.dart';
import 'package:ycbl/widget/send_code_widget.dart';

/// 验证码登陆
class CodeLoginPage extends StatefulWidget {

  //是否作为跟页面存在
  final bool isRootPage;

  const CodeLoginPage({Key key, @required this.isRootPage}) : super(key: key);

  @override
  _CodeLoginPageState createState() => _CodeLoginPageState();
}

class _CodeLoginPageState extends State<CodeLoginPage> {

  // 手机号文本编辑控制器
  final TextEditingController _phoneEditController = TextEditingController();
  // 验证码文本编辑控制器
  final TextEditingController _codeEditController = TextEditingController();
  final BLButtonController _loginBtnController = BLButtonController(initClickable: false,);

  @override
  void initState() {
    //添加监听
    _phoneEditController.addListener(_loginBtnEnable);
    _codeEditController.addListener(_loginBtnEnable);
    super.initState();
  }

  /// 登录按钮是否可点击
  _loginBtnEnable() {
    _loginBtnController.setClickable(_phoneEditController.text.isNotEmpty && _codeEditController.text.isNotEmpty);
  }

  @override
  void dispose() {
    //切记销毁 TextEditingController
    _phoneEditController.dispose();
    _codeEditController.dispose();
    _loginBtnController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BLCommonWhiteAppBar(
        context: context,
        //如果当前是根页面，则隐藏返回按钮
        hideLeftIcon: widget.isRootPage,
        //如果当前是根页面，则显示直接进入按钮，否则不显示
        rightActions: widget.isRootPage ? [
          Padding(
            padding: EdgeInsets.fromLTRB(20, 14, 20, 14),
            child: InkWell(
              onTap: (){
                //进入主页
                Navigator.of(context).pushReplacementNamed(BLRouteName.mainNav);
              },
              child: BorderLabel(
                borderRadius: 20,
                text: '直接进入',
              ),
            ),
          ),
        ] : [],
        onLeftPressed: (){
          Navigator.of(context).pop();
        },
      ),
      backgroundColor: BLColor.whiteColor,
      body: Container(
        padding: EdgeInsets.fromLTRB(45, 10, 45, 50),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '验证码登录',
              style: BLStyle.largeBlackTextStyle.copyWith(fontSize: 26),
            ),

            Text(
              '新用户登录后将自动创建账号',
              style: BLStyle.smallGreyTextStyle.copyWith(fontSize: 14),
            ),
            SizedBox(
              height: 50,
            ),

            LoginTextField(
              controller: _phoneEditController,
              hintText: '请输入手机号',
              inputType: TextInputType.number,
            ),

            SizedBox(height: 20,),

            Stack(
              alignment: Alignment.centerRight,
              children: [
                LoginTextField(
                  controller: _codeEditController,
                  hintText: '请输入验证码',
                  inputType: TextInputType.number,
                ),
                Container(
                  color: BLColor.commonBgColor,
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  margin: EdgeInsets.only(right: 5),
                  child: SendCodeWidget(getPhoneCallback: (){
                    return _phoneEditController.text;
                  }),
                )
              ],
            ),

            Padding(
              padding: EdgeInsets.only(top: 40,),
              child: BLProviderWidget<LoginViewModel>(
                notifierModel: LoginViewModel(Provider.of(context)),
                consumerBuilder: (context, model, child) {
                  if (model.isBusy) {
                    _loginBtnController.setClickable(false);
                  }else {
                    _loginBtnEnable();
                  }

                  return GradientBtn(
                    controller: _loginBtnController,
                    text: model.isBusy ? '登录中...' : '登录',
                    style: BLStyle.middleWhiteTextStyle,
                    gradientDirection: GradientBtn.Top_Bottom,
                    padding: EdgeInsets.symmetric(vertical: 8,),
                    onPressed: () {
                      _login(model);
                    },
                  );
                },
              ),
            )

          ],
        ),
      ),
    );
  }

  ///触发登录
  _login(LoginViewModel model){
    var phone = _phoneEditController.text;
    var code = _codeEditController.text;
    model.login(phone, code, (success) {
      _handleLoginResult(success, model.errorMessage);
    });
  }

  /// 登录结果处理
  _handleLoginResult(bool isSuccess, errMsg) {
    if (isSuccess) {
      ToastUtil.showShortToast(errMsg ?? '登录成功');
      if (widget.isRootPage) { //是根页面，进入主页
        Navigator.of(context).pushReplacementNamed(BLRouteName.mainNav);
      }else if(Navigator.canPop(context)){ // 返回上个页面
        Navigator.of(context).pop();
      }
    }else {
      ToastUtil.showShortToast(errMsg ?? '登录失败');
    }

  }

}
